package com.polight.simplelocation.locationserver;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.nio.charset.Charset;
import java.util.Enumeration;

import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.SocketAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

public class Main {

	private static final int DATA_PORT = 9527;
	private static final int ADMIN_PORT = 9528;

    public static void main(String[] args) throws Exception {
        
        InetAddress ip = null;
        try {
			NetworkInterface networkInterface = NetworkInterface.getByName("eth0");
			Enumeration<InetAddress> cardIpAddresses = networkInterface
			.getInetAddresses();
			while (cardIpAddresses.hasMoreElements()) {
				ip = cardIpAddresses.nextElement();
				if(ip instanceof Inet4Address) {
					break;
				}
			}
		} catch (SocketException e) {
			e.printStackTrace();
		}
		if(ip == null) {
			System.err.println("no ip can be bind");
			System.exit(-1);
		}
		
		SocketAcceptor acceptor = new NioSocketAcceptor();
		acceptor.setReuseAddress( true );
		//DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
		acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory( Charset.forName( "UTF-8" ))));
		// Bind
		acceptor.setHandler(new EchoProtocolHandler());
        acceptor.bind(new InetSocketAddress(ip, DATA_PORT));
        System.out.println("data listening on " + ip.getHostAddress() + ":" + DATA_PORT);
        
        SocketAcceptor adminAcceptor = new NioSocketAcceptor();
        adminAcceptor.setReuseAddress( true );
		//DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
        adminAcceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory( Charset.forName( "UTF-8" ))));
		// Bind
        adminAcceptor.setHandler(new AdminHandler());
        adminAcceptor.bind(new InetSocketAddress(ip, ADMIN_PORT));
        System.out.println("admin listening on " + ip.getHostAddress() + ":" + ADMIN_PORT);
    }
}
